/**
 * Created by moko1988 on 15/12/1.
 */
define([
    'backbone',
    'models/youleGame/list',
    'text!templets/youleGame/list.html',
    'text!templets/youleGame/change.html',
    'text!templets/youleGame/add.html',
    'utils/dataTableUtil',
    'utils/urlUtil',
    'jquerypage',
    'uploadify',
    'select2',
    'moment'
], function(
    BackBone,
    Model,
    Tpl,
    ModalAdd,
    ModalAddIn,
    // ModalReview,
    DataTable,
    UrlUtil
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun', //添加资源
            'click [role=edit]': 'editFun', //修改资源
            'click [role=del]': 'delFun', //删除资源
            'click [role=close]': 'closeFun', //关闭
            'click [role=saveAdd]': 'saveAdd',    //保存添加
            'click [role=refresh]': 'refresh',    //刷新
            'change #pageSize': 'changePageSize', //选择分页宽度
            'click [role=rank]': 'rank', //排序
            'click [role=review]': 'review', //审核
             'click [role=saveChange]': 'saveChange',//保存修改 
            'click [role=recommend]': 'recommend', //推荐
            'click #checkAll': 'checkAll', //全选、取消
            'click input[name=idarr]': 'checkItem', //选择、取消单条记录
            'change #categorySelect': 'changeListCategory_ad',
            'click [role=search]': 'searchCharge',//查询
            'change #bannerCategory': 'changeAddCategory', //添加页面
            'click [role=change-status]': 'changeStatus'
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';
            this.statustype = '';
            this.idArr = [];
            this.categoryid = '';
            $('#pageSize').select2();
            this.renderCategory_ad();
            this.render();
        } ,
        renderCategory_ad: function(){
            var _this = this;
            Model.fetchCategory_ad({
                type: 'post',
                success: function(map) {
                    var opts = '<option value="4">选择分类</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.id] = o;
                        opts += '<option value="'+o.id+'">'+ o.name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#categorySelect').html(opts).prop('disabled',false).select2();
                    $('[role=add]').prop('disabled',false);
                    // _this.render();
                }
            })
        },

        changeListCategory_ad: function(e){
            var $target = $(e.currentTarget);
            var statustype = $target.val(); 
            var _this = this;
            Model.search({
                type: 'post',
                data: {
                    statustype: statustype ,
                    page: this.page,
                    page_size: this.listRows
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                         o.stat = '<input id="statustype" type="hidden" value="'+ o.statustype +'">';

                        o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';

                        var btn_status,
                             rank_up = '<button class="btn btn_rank" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn btn_rank" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        if (i == 0) {
                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                        }
                        if (i == (count - 1)) {
                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        }
                        o.rank = rank_up + rank_down;

                        
                        if(o.isshow == 0){
                            o.isshow = '<font color="red">下架</font>';
                            btn_status = '<button class="btn" role="change-status" data-id="' + o.id+ '" data-type="1">上架</button>';
                        }else if(o.isshow == 1){
                            o.isshow = '<font color="green">上架</font>';
                            btn_status = '<button class="btn" role="change-status" data-id="' + o.id+ '" data-type="0">下架</button>';
                        }

                        o.btns = btn_status;

                        o.picture = '<img src="http://shihai.oss-cn-beijing.aliyuncs.com/'+o.picture+'" style="width:30px; height: 30px">';
                    })
                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '应用名称', 'icon图片','状态', '排序', '操作'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'name'),
                            _.pluck(data,'picture'),
                            _.pluck(data,'isshow'),
                            _.pluck(data,'rank'),
                            _.pluck(data,'btns')
                        );

                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });

                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });

                     var sele = map.sele;
                    if(sele == 1){
                         $('.btn_rank').attr('disabled',true)
                    }else if(sele ==2 ){
                         $('.btn_rank').attr('disabled',false)
                    }
                }
            })     
        },

        /*排序*/

        rank: function(e) {
            var $target = $(e.currentTarget),
                statustype = $('#categorySelect option:checked').attr('value');
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                type: 'post',
                data: {
                    id: id,
                    type: type,
                    statustype: statustype
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                     $('.btn_rank').attr('disabled',false)
                }
            })
        },

        //上下架
        changeStatus: function(e){
            var $target = $(e.currentTarget),
                id = $target.attr('data-id'),
                type = $target.attr('data-type'),
                tip = type == 0 ? '下架' : '上架',
                _this = this;
            jConfirm('确定要' + tip + '该条记录?', function(s) {
                if (s) {
                    Model.isshow({
                        type: 'post',
                        data: {
                            id: id,
                            isshow: type
                        },
                        success: function() {
                            jAlert(tip + '成功', function() {
                                _this.render();
                            })
                        }
                    })
                }
            })
        },

        /*全选、取消*/
        checkAll: function(e) {
            var $target = $(e.currentTarget),
                isCheck = $target.prop('checked'),
                _this = this;
            if (isCheck) {
                $('input[name=idarr]').prop('checked', true);
                $('input[name=idarr]').each(function() {
                    _this.idArr.push($(this).val());
                })
            } else {
                $('input[name=idarr]').prop('checked', false);
                this.idArr = [];
            }
        },
        /*选择、取消单条记录*/
        checkItem: function() {
            this.idArr = [];
            var isCheckAll = true,
                _this = this;
            $('input[name=idarr]').each(function() {
                if ($(this).prop('checked')) {
                    _this.idArr.push($(this).val());
                } else {
                    isCheckAll = false;
                }
            })
            if (isCheckAll) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        },
        /*选择分页宽度*/
        changePageSize: function(e) {
            var $target = $(e.currentTarget),
                val = $target.val();
            this.listRows = val;
            this.render();
        },

        //刷新页面
        refresh: function(e) {
            console.log(1)
        },


        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this,
                statustype = $('#categorySelect option:checked').attr('value') || 5;
            Model.fetchList({
                type: 'post',
                data: {
                    // ad_id:1,
                    page: this.page,
                    page_size: this.listRows,
                    statustype: statustype
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                         o.stat = '<input id="statustype" type="hidden" value="'+ o.statustype +'">';

                        o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';

                        var btn_status,
                             rank_up = '<button class="btn btn_rank" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn btn_rank" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        if (i == 0) {
                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                        }
                        if (i == (count - 1)) {
                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        }
                        o.rank = rank_up + rank_down;

                        
                        if(o.isshow == 0){
                            o.isshow = '<font color="red">下架</font>';
                            btn_status = '<button class="btn" role="change-status" data-id="' + o.id+ '" data-type="1">上架</button>';
                        }else if(o.isshow == 1){
                            o.isshow = '<font color="green">上架</font>';
                            btn_status = '<button class="btn" role="change-status" data-id="' + o.id+ '" data-type="0">下架</button>';
                        }

                        o.btns = btn_status;

                        o.picture = '<img src="http://shihai.oss-cn-beijing.aliyuncs.com/'+o.picture+'" style="width:30px; height: 30px">';
                    })
                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '应用名称', 'icon图片','状态', '排序', '操作'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'name'),
                            _.pluck(data,'picture'),
                            _.pluck(data,'isshow'),
                            _.pluck(data,'rank'),
                            _.pluck(data,'btns')
                        );
                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });
                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });
             
                    var sele = map.sele;
                    if(sele == 1){
                         $('.btn_rank').attr('disabled',true)
                    }else if(sele ==2 ){
                         $('.btn_rank').attr('disabled',false)
                    }
                      
                }
            })
        },
        /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.render();
        },
       //添加
        

        addFun: function() {
            window.location.hash = 'view/youleGame-add'
        },

         editFun: function(e) {
            if (this.idArr.length) {
                    var 
                        id = this.idArr[0],

                        params = UrlUtil.parse2Str({
                            id: id
                        }),
                        url = 'view/youleGame-change/' + params;
                    location.hash = url;

            }else {
                jAlert('请选择要操作的数据');
            }
            
        },


        /*推荐/取消推荐*/
        recommend: function(e){
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                Model.recommend({
                    data: {
                        id: id,
                        type: type
                    },
                    success: function(map) {
                        jAlert('操作成功！', function() {
                            _this.idArr = [];
                            _this.render();
                        });
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }
        },
        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.parents('tr').attr('data-id'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                jConfirm('确定要删除？', function(s) {
                    if (s) {
                        Model.delete({
                            type: 'post',
                            data: {
                                id: id
                            },
                            success: function(map) {
                                jAlert('删除成功', function() {
                                    _this.idArr = [];
                                    _this.render();
                                })
                            }
                        })
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }

        },



         checkForm: function() {
            var $form = $('[role=form]'),
                $gameName = $form.find('input[name=gameName]'),
                $layerName = $form.find('input[name=layerName]'),
                $gameLink = $form.find('input[name=gameLink]'),
                $popularity = $form.find('input[name=popularity]'),
                $content = $form.find('input[name=content]'),

                //下拉框
                $select = $('#AllAdvertisers');
                $selOpt = $('#AllAdvertisers option:selected');

                getTip = function(e) {
                    var text = e.siblings('label.control-label').html();
                    // text = text.substr(0, text.length - 1);
                    return text;
                },
                errShow = function(e, msg) {
                    var $err = e.siblings('em');
                    $err.html(msg).css("opacity", '1');
                    $err.stop(0, 0).animate({
                        "opacity": 0
                    }, 3500);
                    rest = false;
                },
                rest = true;
                
                //游戏名称
                if ($.trim($gameName.val()) == '') {
                    errShow($gameName, '请填写' + getTip($gameName));
                } else if ($gameName.val().length < 2 || $gameName.val().length > 20) {
                    errShow($gameName, '请填写2-20个字符');
                }
    
                //游戏链接
                if ($.trim($gameLink.val()) == '') {
                    errShow($gameLink, '请填写' + getTip($gameLink));
                } 


                //下拉框
                if ($.trim($selOpt.val()) == '') {
                     errShow($select, '请选择广告主');
                } 


                //分层比例
                var reg = /^([0-9]\d?|100)$/;
                var result = reg.test($layerName.val());
                if(!result){
                     errShow($layerName, '请填写0-100中间的数字');
                }

                //人气【只能填写数字】
                var reg = /^\d+(\.\d+)?$/;
                var result = reg.test($popularity.val());
                if(!result){
                     errShow($popularity, '请填写数字');
                }



            return rest;
        },

        /*编辑图片回显*/
        imgEcho: function($target, val) {
         
            var $wrap = $target.parent('[role=upimg]'),
                $info = $wrap.find('.file-info'),
                $val = $wrap.find('.file-val');

            $target.val(val);
            $info.addClass('hide');
            $val.removeClass('hide').find('img').attr('src', 'http://shihai.oss-cn-beijing.aliyuncs.com/' + val);
            $wrap.find('.uploadify').css('z-index', -1);
        },
         /*初始化uploadify上传按钮*/
        uploadifyIni: function() {
            var _this = this;
            $('input[role=file-upload]').each(function() {
                var $this = $(this),
                    $wrap = $this.parents('[role=upimg]'),
                    $fileCanvas = $wrap.find('.file-canvas'),
                    $info = $fileCanvas.find('.file-info'),
                    $loading = $fileCanvas.find('.file-loading'),
                    $val = $fileCanvas.find('.file-val'),
                    $input = $wrap.find('input.file-input'),
                    index = $('[role=upimg]').index($wrap);
                $loading.html(loading2);
                $(this).attr('id', 'file-upload-' + index);
                $this.uploadify({
                    height: 23,
                    width: 43,
                    removeTimeout: 1,
                    buttonText: '上传',
                    fileTypeExts: '*',
                    fileSizeLimit: '4MB', //上传文件大小限制
                    multi: false, //是否可以上传多个文件
                     swf: '/Public/admin/images/uploadify.swf', //上传flash地址（注意路径）
                    uploader: adminPath + '/index/uploadfile', //上传数据处理文件Ajax（注意路径）
                    /*开始上传之前触发*/
                    onUploadStart: function() {
                        $info.addClass('hide');
                        $loading.removeClass('hide');
                        $wrap.find('.uploadify').css('z-index', -1);
                    },
                    /*上传完成之后触发*/
                    onUploadSuccess: function(file, data, response) {
                        if (response) {
                            data = $.parseJSON(data);
                            if (data.code == 1) {
                                $input.val(data.filename);
                                $val.removeClass('hide');
                                $val.find('img').attr('src', 'http://shihai.oss-cn-beijing.aliyuncs.com/' + data.filename);
                                $loading.addClass('hide');
                            } else {
                                jAlert(data.msg, function() {
                                    $info.removeClass('hide');
                                    $loading.addClass('hide');
                                    $wrap.find('.uploadify').css('z-index', 1);
                                });
                            }
                        }
                    }
                })
                /*鼠标经过上传完的图片隐藏展示删除按钮*/
                $val.hover(function() {
                    $(this).find('i').show();
                }, function() {
                    $(this).find('i').hide();
                });
                /*鼠标经过上传面板隐藏展示上传按钮*/
                $fileCanvas.hover(function() {
                    $(this).find('.uploadify-button ').show();
                }, function() {
                    $(this).find('.uploadify-button ').hide();
                });
                /*点击删除图片按钮*/
                $val.find('i').click(function() {
                    _this.resetfileCanvas($wrap);
                });
            })
        },
        /*还原上传面板*/
        resetfileCanvas: function($wrap) {
            $wrap.find('input.file-input').val('');
            $wrap.find('.file-val').addClass('hide');
            $wrap.find('.file-info').removeClass('hide');
            $wrap.find('.uploadify').css('z-index', 1);
        },
        /*初始化uploadify上传按钮(多图上传)*/
        uploadifyMultiIni: function() {
            var _this = this;
            $('#file-upload-multi').uploadify({
                height: 23,
                width: 143,
                buttonText: '多图上传',
                fileTypeExts: '*',
                fileSizeLimit: '4MB', //上传文件大小限制
                multi: true, //是否可以上传多个文件
                swf: ROOT_PATH + '/Public/admin/images/uploadify.swf', //上传flash地址（注意路径）
                uploader: ADMIN_PATH + '/index/uploadfile', //上传数据处理文件Ajax（注意路径）
                /*开始上传之前触发*/
                onUploadStart: function() {
                    if(_this.MultNO >= _this.maxMult){
                        $('#file-upload-multi').uploadify('cancel', '*');//清除剩余的上传队列
                        jAlert('最多只能上传' + _this.maxMult + '张!');
                    }
                },
                /*上传完成之后触发*/
                onUploadSuccess: function(file, data, response) {
                    if (response) {
                        data = $.parseJSON(data);
                        if (data.code == 1) {
                            _this.MultNO++;
                            var imgList = '<div class="img-list">';
                            imgList += '<input role="img-list" type="hidden" value="'+ data.filename +'">';
                            imgList += '<img src="' + PIC_PATH + data.filename + '">';
                            imgList += '<i title="删除"></i>';
                            imgList += '</div>';
                            $('#multi-warp').append(imgList);

                        }
                    }
                }
            })
            /*鼠标经过上传完的图片隐藏展示删除按钮*/
            $('#multi-warp').on('mousemove', '.img-list', function(){
                $(this).find('i').show();
            });
            $('#multi-warp').on('mouseout', '.img-list', function(){
                $(this).find('i').hide();
            });
            /*点击删除图片按钮*/
            $('#multi-warp').on('click','.img-list i', function(){
                var $wrap = $(this).parent();
                $wrap.remove();
                _this.MultNO--;
            })
        }


    })
    return view;
})

